const express = require('express');
const cors = require('cors');
const EventEmitter = require('events');

// 创建事件发射器用于日志通知
const eventEmitter = new EventEmitter();

// 默认配置
let serverConfig = {
    port: 3000,
    delay: 5000,
    defaultResult: 'PASS',
    errorPattern: 'ERROR'
};

// 服务器实例
let server = null;
let app = null;

// 模拟MES响应延迟
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

// 创建Express应用
function createApp() {
    const app = express();

    // 启用 CORS 和 JSON 解析
    app.use(cors());
    app.use(express.json());

    // 记录所有请求
    app.use((req, res, next) => {
        // console.log('Request received:', req.method, req.path);
        // console.log('Request body:', req.body);
        next();
    });

    // SN_CheckIn 事件处理
    app.post('/api/events', async (req, res) => {
        const requestData = req.body;
        await delay(serverConfig.delay);

        const {SN, CarrierID, EventID = ''} = requestData;
        // 使用配置的错误模式进行验证
        const isValid = SN && !SN.includes(serverConfig.errorPattern);
        const result = isValid ? serverConfig.defaultResult : 'FAIL';

        const responseData = {
            EventID: EventID,
            Result: result,
            MSG: result,
            SN: SN,
            CarrierID: CarrierID
        };

        // 发出日志事件
        eventEmitter.emit('request-log', {
            request: requestData,
            response: responseData
        });

        res.json(responseData);
    });

    return app;
}

// 启动服务器
export function startMockServer(config = {}) {
    if (server) {
        return {success: false, error: '服务器已在运行'};
    }
    // 更新配置
    serverConfig = {...serverConfig, ...config};

    try {
        app = createApp();
        server = app.listen(serverConfig.port, () => {
            console.log(`Mock MES服务器运行在 http://localhost:${serverConfig.port}`);
        });

        return {
            success: true,
            port: serverConfig.port
        };
    } catch (error) {
        console.error('启动服务器失败:', error);
        return {
            success: false,
            error: error.message
        };
    }
}

// 停止服务器
export function stopMockServer() {
    if (!server) {
        return {success: false, error: '服务器未运行'};
    }

    try {
        server.close();
        server = null;
        app = null;
        console.log('Mock MES服务器已停止');
        return {success: true};
    } catch (error) {
        console.error('停止服务器失败:', error);
        return {
            success: false,
            error: error.message
        };
    }
}

// 更新配置
export function updateMockConfig(config = {}) {
    try {
        serverConfig = {...serverConfig, ...config};
        return {success: true};
    } catch (error) {
        console.error('更新配置失败:', error);
        return {
            success: false,
            error: error.message
        };
    }
}

// 获取服务器状态
export function getMockStatus() {
    return {
        running: server !== null,
        port: serverConfig.port
    };
}

// 获取服务器配置
export function getMockConfig() {
    return {...serverConfig};
}

// 添加日志监听器
export function addMockLogListener(callback) {
    eventEmitter.on('request-log', callback);
}

// 移除日志监听器
export function removeMockLogListener(callback) {
    if (callback) {
        eventEmitter.off('request-log', callback);
    } else {
        eventEmitter.removeAllListeners('request-log');
    }
}
